from datetime import date

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from apps.goods.models import GoodsCategory, SKU
from apps.contents.models import ContentCategory
from utils.goods import get_categories, get_goods_specs
from utils.goods import get_breadcrumb
from apps.goods.models import GoodsVisitCount


# Create your views here.
class IndexView(View):
    def get(self, request):
        # 获取商品分类数据
        categories = get_categories()
        # 广告数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
        context = {
            'categories': categories,
            'contents': contents,
        }
        return render(request, 'index.html', context)


##############列表页##############
class ListView(View):
    def get(self, request, category_id):
        # 排序字段
        ordering = request.GET.get('ordering')
        # 每页多少条数据
        page_size = request.GET.get('page_size')
        # 要第几页数据
        page = request.GET.get('page')
        # 获取分类id,根据id查询分类对象
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        # 获取面包屑数据
        breadcrumb = get_breadcrumb(category)
        # 查询分类对应的sku数据然后排序然后分页
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)
        # 分页
        from django.core.paginator import Paginator
        paginator = Paginator(skus, per_page=page_size)
        # 获取指定页码的数据
        page_skus = paginator.page(page)
        sku_list = []
        for sku in page_skus.object_list:
            sku_list.append({
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image.url,
            })
        # 获取总页数
        total_num = paginator.num_pages
        # 构造响应数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'breadcrumb': breadcrumb, 'list': sku_list, 'count': total_num})


#################详情页################
class DetailView(View):

    def get(self, request, sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            pass
        # 1.分类数据
        categories = get_categories()
        # 2.面包屑
        breadcrumb = get_breadcrumb(sku.category)
        # 3.SKU信息
        # 4.规格信息
        goods_specs = get_goods_specs(sku)

        context = {

            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,

        }
        return render(request, 'detail.html', context)


# 这个函数帮助我们数据库查询渲染HTML页面,然后把渲染的HTML写入到指定文件
import time


def generic_meiduo_index():
    print('----------%s----------' % time.ctime())
    # 获取商品分类数据
    categories = get_categories()
    # 广告数据
    contents = {}
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
    context = {
        'categories': categories,
        'contents': contents,
    }
    #加载渲染的模板
    from django.template import loader
    index_template = loader.get_template('index.html')
    #把数据给模板
    from django.conf import settings
    import os
    index_html_data = index_template.render(context)
    #写入到指定文件
    file_path = os.path.join(os.path.dirname(settings.BASE_DIR), 'front_end_pc/index.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(index_html_data)


#####分类商品统计#####
class CategoryVisitCountView(View):

    def post(self, request, category_id):
        # 1.接收分类id
        # 2.验证参数（验证分类id）
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '没有此分类'})
        # 3.查询当天 这个分类的记录有没有

        today = date.today()
        try:
            gvc = GoodsVisitCount.objects.get(category_id=category_id, date=today)
        except GoodsVisitCount.DoesNotExist:
            # 4. 没有新建数据
            GoodsVisitCount.objects.create(category_id=category_id,
                                           date=today,
                                           count=1)
        else:
            # 5. 有的话更新数据
            gvc.count += 1
            gvc.save()
        # 6. 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})
